// minepackage/pages/mycenter/mycenter.js
const app = getApp()
const url = app.globalData.baseUrl
import Toast from '@vant/weapp/toast/toast'
import { addMineInfo, getUserDetail } from '../../api/myCenterApi.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userJSON: null,
    //用户信息
    userInfo: {
      headImage: '',
      account: '账号',
      userName: '去填写',
      nickName: '去填写',
      sex: '去填写',
      birthday: '去选择',
      address: '去选择',
      addressDetail: '去填写',
      phone: '去绑定',
      email: '去绑定'
    },
    headImageTmp: '',
    timeStampDateVal: ''
  },

  onShow() {
    const userDataStr = wx.getStorageSync('user_data')
    if (userDataStr == null || userDataStr == '') {
      wx.reLaunch({
        url: '/loginpackage/pages/login/login',
      })
    } else {
      this.setData({
        userJSON: JSON.parse(userDataStr)
      })
      this.getUserDetail()
    }

  },

  /**
   * 点击按钮更换头像
   */
  editHeadImage() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        Toast.loading({
          message: '正在上传...',
          forbidClick: true,
        });
        //上传文件
        wx.uploadFile({
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          url: url + '/user/uploadHeadImg',
          header: {
            token: wx.getStorageSync('token')
          },
          success(res) {
            Toast.clear()
            const data = res.data
            const dataJSON = JSON.parse(data)
            //获取文件地址
            that.setData({
              headImageTmp: dataJSON.msg
            })
            const params = {
              id: that.data.userInfo.id,
              headImage: dataJSON.msg
            }
            //修改用户信息
            addMineInfo(params, res => {
              that.getUserDetail()
            }, e => {
              console.log(e)
            })
          }
        })
        Toast.clear()
      }
    })
  },

  /**
   * 
   * 获取个人信息
   */
  getUserDetail() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    })
    //请求参数
    let params = {
      id: this.data.userJSON.id,
    }
    getUserDetail(params, (res) => {
      const user = res.data
      this.setData({
        userInfo: user
      })
      this.timeStampToDate(user.birthday)
    }, (e) => {
      console.log(e)
    })
  },

  /**
   * 时间戳转为日期
   */
  timeStampToDate(timsStamp) {
    const date = new Date(timsStamp)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    this.setData({
      timeStampDateVal: year + '年' + month + '月' + day + '日'
    })
  },

})